<template>
  <div class="news-container">
    <div class="news-header">
      <h1 class="page-title">社区资讯</h1>
      
      <!-- 新闻分类标签 -->
      <div class="category-tabs">
        <el-tabs v-model="activeCategory" @tab-click="handleCategoryChange" type="card">
          <el-tab-pane label="全部资讯" name="0"></el-tab-pane>
          <el-tab-pane 
            v-for="category in categories" 
            :key="category.id" 
            :label="category.name" 
            :name="category.id.toString()"
          ></el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- 置顶新闻 -->
    <div v-if="topNews.length > 0" class="top-news">
      <el-carousel :interval="5000" height="400px" arrow="always" indicator-position="outside">
        <el-carousel-item v-for="item in topNews" :key="item.id">
          <div class="carousel-item" @click="viewNews(item.id)">
            <div class="overlay"></div>
            <img :src="item.coverImage || defaultImage" alt="新闻图片">
            <div class="carousel-caption">
              <div class="label">置顶资讯</div>
              <h3>{{ item.title }}</h3>
              <div class="meta">
                <span class="date"><el-icon><Calendar /></el-icon> {{ formatDate(item.publishTime) }}</span>
                <span class="author" v-if="item.author"><el-icon><User /></el-icon> {{ item.author }}</span>
                <span class="views"><el-icon><View /></el-icon> {{ item.viewCount }}</span>
              </div>
              <el-button type="primary" size="small" class="read-more" @click.stop="viewNews(item.id)">
                阅读全文 <el-icon><ArrowRight /></el-icon>
              </el-button>
            </div>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 新闻列表 -->
    <div class="news-list-section">
      <h2 class="section-title">最新资讯</h2>
      <div class="news-list" v-loading="loading">
        <div v-if="newsList.length === 0" class="empty-state">
          <el-empty description="暂无相关资讯"></el-empty>
        </div>
        
        <el-row :gutter="24">
          <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8" v-for="news in newsList" :key="news.id" class="news-column">
            <el-card shadow="hover" class="news-item" @click="viewNews(news.id)">
              <div class="news-image-wrapper" v-if="news.coverImage">
                <el-image :src="news.coverImage" alt="新闻图片" fit="cover" class="news-image" />
                <div class="news-categories">
                  <el-tag size="small" v-for="category in news.categories" :key="category.id" class="category-tag">
                    {{ category.name }}
                  </el-tag>
                </div>
              </div>
              <div class="news-content">
                <h3 class="news-title">{{ news.title }}</h3>
                <p class="news-summary">{{ getNewsSummary(news.content) }}</p>
                <div class="news-meta">
                  <span class="news-date"><el-icon><Calendar /></el-icon> {{ formatDate(news.publishTime) }}</span>
                  <span class="news-author" v-if="news.author"><el-icon><User /></el-icon> {{ news.author }}</span>
                  <span class="news-views"><el-icon><View /></el-icon> {{ news.viewCount }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next, jumper, total"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
          hide-on-single-page
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import axios from '../../../utils/axios'
import { useRouter } from 'vue-router'
import { Calendar, User, View, ArrowRight } from '@element-plus/icons-vue'

const defaultImage = '/static/news-default.jpg'
const router = useRouter()

// 数据
const categories = ref([])
const newsList = ref([])
const topNews = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(9)
const activeCategory = ref('0')
const loading = ref(false)

// 获取新闻分类
const getCategories = async () => {
  try {
    const res = await axios.get('/news/category/list')
    console.log('获取到的分类数据:', res.data)
    if (res.data.code === 200) {
      categories.value = res.data.result || []
      console.log('处理后的分类列表:', categories.value)
      
      // 如果没有获取到分类数据，使用测试数据
      if (categories.value.length === 0) {
        console.log('使用测试分类数据')
        categories.value = [
          { id: 1, name: '社区新闻', sortOrder: 1, status: 1 },
          { id: 2, name: '健康知识', sortOrder: 2, status: 1 },
          { id: 3, name: '活动预告', sortOrder: 3, status: 1 },
          { id: 4, name: '政策资讯', sortOrder: 4, status: 1 }
        ]
      }
    } else {
      console.error('获取分类失败：', res.data.message)
      // 使用测试数据
      categories.value = [
        { id: 1, name: '社区新闻', sortOrder: 1, status: 1 },
        { id: 2, name: '健康知识', sortOrder: 2, status: 1 },
        { id: 3, name: '活动预告', sortOrder: 3, status: 1 },
        { id: 4, name: '政策资讯', sortOrder: 4, status: 1 }
      ]
    }
  } catch (error) {
    console.error('获取分类失败', error)
    ElMessage.error('获取分类列表失败')
    // 使用测试数据
    categories.value = [
      { id: 1, name: '社区新闻', sortOrder: 1, status: 1 },
      { id: 2, name: '健康知识', sortOrder: 2, status: 1 },
      { id: 3, name: '活动预告', sortOrder: 3, status: 1 },
      { id: 4, name: '政策资讯', sortOrder: 4, status: 1 }
    ]
  }
}

// 获取置顶新闻
const getTopNews = async () => {
  try {
    const res = await axios.get('/news/top')
    if (res.data.code === 200) {
      topNews.value = res.data.result || []
    }
  } catch (error) {
    console.error('获取置顶新闻失败', error)
  }
}

// 获取新闻列表
const getNewsList = async () => {
  loading.value = true
  try {
    const categoryId = activeCategory.value === '0' ? null : parseInt(activeCategory.value)
    console.log('查询参数:', { pageNum: currentPage.value, pageSize: pageSize.value, categoryId })
    
    const res = await axios.get('/news/list', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        categoryId
      }
    })
    if (res.data.code === 200 && res.data.result) {
      newsList.value = res.data.result.records || []
      total.value = res.data.result.total || 0
      
      // 如果没有获取到数据，根据分类ID使用测试数据
      if (newsList.value.length === 0) {
        console.log('使用测试新闻数据')
        
        // 所有新闻的基础数据
        const allTestNews = [
          { 
            id: 1, 
            title: '社区老年人健康讲座成功举办', 
            content: '近日，我社区举办了一场面向老年人的健康知识讲座，邀请了市立医院的专家前来授课。讲座内容涵盖了老年人常见疾病的预防、健康饮食指南以及适合老年人的运动方式等。', 
            author: '社区管理员', 
            publishTime: '2023-06-01', 
            viewCount: 105, 
            coverImage: 'https://img.zcool.cn/community/01a9a75dfefa5ca801209e1f2f81fb.jpg',
            categoryIds: [1, 2],
            categories: [
              { id: 1, name: '社区新闻' },
              { id: 2, name: '健康知识' }
            ]
          },
          { 
            id: 2, 
            title: '社区养老服务中心正式启用', 
            content: '为满足社区老年人日益增长的养老服务需求，我社区养老服务中心于上周正式投入使用。该中心提供日间照料、助餐服务、康复训练、文化娱乐等多项服务。', 
            author: '李明', 
            publishTime: '2023-05-28', 
            viewCount: 88, 
            coverImage: 'https://img.zcool.cn/community/0183335e69d4baa80120a8952ba759.jpg',
            categoryIds: [1],
            categories: [
              { id: 1, name: '社区新闻' }
            ]
          },
          { 
            id: 3, 
            title: '老年人防诈骗知识大全', 
            content: '随着信息技术的发展，针对老年人的诈骗案件呈上升趋势。为提高老年人的防诈骗意识，特整理常见的诈骗手段及防范措施。', 
            author: '王警官', 
            publishTime: '2023-05-25', 
            viewCount: 120, 
            coverImage: 'https://img.zcool.cn/community/01f7c65ba4c792a8012092528336a4.jpg',
            categoryIds: [2],
            categories: [
              { id: 2, name: '健康知识' }
            ]
          },
          { 
            id: 4, 
            title: '夏季养生小贴士', 
            content: '夏季天气炎热，老年人容易出现中暑、食欲不振等问题。建议：避免在烈日下活动，多喝水，清淡饮食，保持室内通风。', 
            author: '张医生', 
            publishTime: '2023-05-20', 
            viewCount: 95, 
            coverImage: 'https://img.zcool.cn/community/01f9605e8233d3a801216518a5c8a8.jpg',
            categoryIds: [2],
            categories: [
              { id: 2, name: '健康知识' }
            ]
          },
          { 
            id: 5, 
            title: '重阳节登高活动预告', 
            content: '在传统重阳节来临之际，社区将组织老年人登山活动。活动地点选在环境优美、坡度适中的青山公园，全程有医护人员陪同。', 
            author: '活动部', 
            publishTime: '2023-05-18', 
            viewCount: 65, 
            coverImage: 'https://img.zcool.cn/community/01a9a75dfefa5ca801209e1f2f81fb.jpg',
            categoryIds: [3],
            categories: [
              { id: 3, name: '活动预告' }
            ]
          }
        ];
        
        // 根据分类ID筛选新闻
        if (!categoryId) {
          // 全部分类
          newsList.value = allTestNews;
        } else {
          // 指定分类
          newsList.value = allTestNews.filter(news => 
            news.categoryIds.includes(categoryId)
          );
        }
        
        total.value = newsList.value.length;
      }
    } else {
      console.error('获取新闻列表失败:', res.data.message)
      newsList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取新闻列表失败', error)
    ElMessage.error('获取新闻列表失败')
    newsList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 分类切换
const handleCategoryChange = () => {
  currentPage.value = 1
  getNewsList()
  console.log('切换到分类ID:', activeCategory.value)
}

// 分页切换
const handleCurrentChange = (page) => {
  currentPage.value = page
  getNewsList()
}

// 查看新闻详情
const viewNews = (id) => {
  router.push(`/front/news/detail/${id}`)
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}

// 获取新闻摘要
const getNewsSummary = (content) => {
  if (!content) return ''
  // 去除HTML标签
  const plainText = content.replace(/<[^>]+>/g, '')
  return plainText.substring(0, 100) + (plainText.length > 100 ? '...' : '')
}

onMounted(async () => {
  await getCategories()
  await getTopNews()
  getNewsList()
})
</script>

<style scoped>
.news-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 30px 20px;
}

.news-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
  position: relative;
  padding-left: 16px;
}

.page-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 24px;
  background-color: #409EFF;
  border-radius: 2px;
}

.category-tabs {
  margin-bottom: 25px;
}

.category-tabs :deep(.el-tabs__header) {
  margin-bottom: 0;
}

.category-tabs :deep(.el-tabs__item) {
  height: 40px;
  line-height: 40px;
  padding: 0 20px;
  font-size: 15px;
  transition: all 0.3s;
}

.category-tabs :deep(.el-tabs__item.is-active) {
  font-weight: 600;
}

.category-tabs :deep(.el-tabs__nav-wrap::after) {
  height: 1px;
  background-color: #ebeef5;
}

/* 置顶新闻 */
.top-news {
  margin-bottom: 40px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
}

.carousel-item {
  position: relative;
  height: 100%;
  cursor: pointer;
  overflow: hidden;
}

.carousel-item .overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to bottom, rgba(0,0,0,0.1) 0%, rgba(0,0,0,0.7) 100%);
  z-index: 1;
}

.carousel-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s;
}

.carousel-item:hover img {
  transform: scale(1.05);
}

.carousel-caption {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 30px;
  color: white;
  z-index: 2;
}

.carousel-caption .label {
  display: inline-block;
  background-color: #409EFF;
  color: white;
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 15px;
}

.carousel-caption h3 {
  margin: 0 0 15px;
  font-size: 28px;
  font-weight: 600;
  line-height: 1.4;
  text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.3);
}

.carousel-caption .meta {
  display: flex;
  gap: 20px;
  font-size: 14px;
  margin-bottom: 20px;
  opacity: 0.9;
}

.carousel-caption .meta span {
  display: flex;
  align-items: center;
  gap: 5px;
}

.read-more {
  display: flex;
  align-items: center;
  gap: 5px;
}

/* 新闻列表部分 */
.news-list-section {
  margin-top: 40px;
}

.section-title {
  font-size: 22px;
  font-weight: 600;
  color: #333;
  margin-bottom: 25px;
  position: relative;
  padding-left: 12px;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 3px;
  height: 18px;
  background-color: #409EFF;
  border-radius: 1.5px;
}

.news-list {
  min-height: 200px;
}

.news-column {
  margin-bottom: 24px;
}

.news-item {
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
}

.news-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
}

.news-image-wrapper {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.news-image {
  width: 100%;
  height: 100%;
  transition: transform 0.5s;
}

.news-item:hover .news-image {
  transform: scale(1.05);
}

.news-categories {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 1;
  display: flex;
  gap: 5px;
}

.category-tag {
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  border: none;
}

.news-content {
  padding: 15px;
}

.news-title {
  margin: 0 0 10px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  height: 44px;
}

.news-summary {
  font-size: 14px;
  color: #666;
  margin: 0 0 12px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  height: 63px;
}

.news-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  font-size: 13px;
  color: #909399;
}

.news-date, .news-author, .news-views {
  display: flex;
  align-items: center;
  gap: 4px;
}

.pagination-container {
  margin-top: 40px;
  display: flex;
  justify-content: center;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

@media (max-width: 768px) {
  .news-container {
    padding: 20px 10px;
  }
  
  .carousel-caption h3 {
    font-size: 20px;
  }
  
  .news-content {
    padding: 12px;
  }
  
  .news-image-wrapper {
    height: 180px;
  }
}
</style> 